package com.example.rtm.busline;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.amap.api.services.busline.BusLineItem;
import com.amap.api.services.busline.BusLineQuery;
import com.amap.api.services.busline.BusLineResult;
import com.amap.api.services.busline.BusLineSearch;
import com.amap.api.services.busline.BusStationItem;
import com.amap.api.services.core.AMapException;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.Subscription;

// 爬公交线路APK
public class MainActivity extends AppCompatActivity implements View.OnClickListener, BusLineSearch.OnBusLineSearchListener {
    private ProgressDialog progDialog = null;// 进度框
    private EditText searchName;// 输入公交线路名称
    private int currentpage = 0;// 公交搜索当前页，第一页从0开始
    private BusLineResult busLineResult;// 公交线路搜索返回的结果
    private List<BusLineItem> lineItems = null;// 公交线路搜索返回的busline
    private BusLineQuery busLineQuery;// 公交线路查询的查询类

    private BusLineSearch busLineSearch;// 公交线路列表查询
    private String mCityName;
    private EditText mSelectCity;
    private Subscription mBusLineReuqest;

    private JSONObject object;  //JSONObject对象，处理一个一个的对象
    private JSONObject object2;
    private JSONObject object1;
    private JSONArray jsonArray;//JSONObject对象，处理一个一个集合或者数组
    private JSONArray jsonArray1;//JSONObject对象，处理一个一个集合或者数组
    private JSONArray jsonArray2;//JSONObject对象，处理一个一个集合或者数组
    private String jsonString;  //保存带集合的json字符串
    private String jsonString2;//不带集合的json字符串

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }


    /**
     * 初始化AMap对象
     */
    private void init() {

        Button searchByName = (Button) findViewById(R.id.searchbyname);
        searchByName.setOnClickListener(this);
        mSelectCity = (EditText) findViewById(R.id.cityName);
        searchName = (EditText) findViewById(R.id.busName);
    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBusLineReuqest != null && mBusLineReuqest.isUnsubscribed()){
            mBusLineReuqest.unsubscribe();
        }

    }

    /**
     * 公交线路搜索
     */
    public void searchLine() {
        currentpage = 0;// 第一页默认从0开始
        showProgressDialog();
        String search = searchName.getText().toString().trim();
        mCityName = mSelectCity.getText().toString();
        if ("".equals(search)) {
            search = "B22";
            searchName.setText(search);
        }
        busLineQuery = new BusLineQuery(search, BusLineQuery.SearchType.BY_LINE_NAME, mCityName);// 第一个参数表示公交线路名，第二个参数表示公交线路查询，第三个参数表示所在城市名或者城市区号
        busLineQuery.setPageSize(10);// 设置每页返回多少条数据
        busLineQuery.setPageNumber(currentpage);// 设置查询第几页，第一页从0开始算起
        busLineSearch = new BusLineSearch(this, busLineQuery);// 设置条件
        busLineSearch.setOnBusLineSearchListener(this);// 设置查询结果的监听
        busLineSearch.searchBusLineAsyn();// 异步查询公交线路名称
        // 公交站点搜索事例
        /*
		 * BusStationQuery query = new BusStationQuery(search,cityCode);
		 * query.setPageSize(10); query.setPageNumber(currentpage);
		 * BusStationSearch busStationSearch = new BusStationSearch(this,query);
		 * busStationSearch.setOnBusStationSearchListener(this);
		 * busStationSearch.searchBusStationAsyn();
		 */
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在搜索:\n");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    /**
     * 公交线路搜索返回的结果显示在dialog中
     */
    public void showResultList(final List<BusLineItem> busLineItems) {
        BusLineDialog busLineDialog = new BusLineDialog(this, busLineItems);
        busLineDialog.onListItemClicklistener(new OnListItemlistener() {
            @Override
            public void onListItemClick(BusLineDialog dialog,
                                        final BusLineItem item) {
                showProgressDialog();

                String lineId = item.getBusLineId();// 得到当前点击item公交线路id
                String OriginatingStation = item.getOriginatingStation();
                String TerminalStation = item.getTerminalStation();
                String feescale = "";
                List<Root> roots = new ArrayList<Root>();
                String BasicPrice = "";
                String TotalPrice = "";
                String name = "";
                String end = "";
                String start = "";
                List<Root.ffx> ffxList = new ArrayList<Root.ffx>();
                List<Root.zfx> zfxList = new ArrayList<Root.zfx>();
                for (BusLineItem busLineItem : busLineItems) {
                    Log.d("MainActivity", "公交类型=======@@" + busLineItem.getBusLineType());
                    Log.d("MainActivity", "所有的公交id=====***" + busLineItem.getBusLineId());
                    if (busLineItem.getBusLineId().equals(lineId)) {
                        BasicPrice = busLineItem.getBasicPrice() + "";
                        TotalPrice = busLineItem.getTotalPrice() + "";
                        name = busLineItem.getBusLineName().substring(0, busLineItem.getBusLineName().indexOf("("));
                        end = busLineItem.getTerminalStation();
                        start = busLineItem.getOriginatingStation();

                        Log.d("MainActivity", "公交线路名字====1" + name);
                        Log.d("MainActivity", "busLineItem.getBasicPrice():=====1开始价格=$:" + BasicPrice);
                        Log.d("MainActivity", "busLineItem.getTotalPrice():=====1总价格=$:" + TotalPrice);
                        Log.d("MainActivity", "busLineItem.getOriginatingStation()获取的公交起始站点====1:" + busLineItem.getOriginatingStation());
                        Log.d("MainActivity", "busLineItem.getTerminalStation()获取的公交终点站点====1:" + busLineItem.getTerminalStation());
                        if (busLineItem.getBasicPrice() == busLineItem.getTotalPrice()) {
                            feescale = "1";
                        } else {
                            feescale = "2";
                        }
                        Log.d("BuslineActivity", "选中的公交feescale=公交线路======1: " + feescale);
                        Log.d("BuslineActivity", "选中的公交的所有站点信息=公交线路======1" + busLineItem.getBusLineId());
                        for (BusStationItem busStationItem : busLineItem.getBusStations()) {
                            Root.ffx ffx = new Root.ffx();
                            Log.d("BuslineActivity", "选中的公交的所有站点信息=======33" + busStationItem.getBusStationName());
                            Log.d("BuslineActivity", "选中的公交的所有站点信息=======33" + busStationItem.getLatLonPoint());
                            String lat = busStationItem.getLatLonPoint().getLatitude() + "";
                            String lon = busStationItem.getLatLonPoint().getLongitude() + "";
                            ffx.setLat(lat);
                            ffx.setLon(lon);
                            ffx.setName(busStationItem.getBusStationName());
                            ffxList.add(ffx);
                            Log.d("BuslineActivity", "选中的公交的所有站点经度=======34: " + lon);
                            Log.d("BuslineActivity", "选中的公交的所有站点信息=======34: " + lat);
                        }
                    } else if (!TextUtils.isEmpty(OriginatingStation) && !TextUtils.isEmpty(TerminalStation)) {
                        boolean o = busLineItem.getOriginatingStation().equals(TerminalStation);
                        boolean b = busLineItem.getTerminalStation().equals(OriginatingStation);
                        if (o && b) {
                            Log.d("MainActivity", "busLineItem.getBasicPrice():=====2开始价格=$:" + busLineItem.getBasicPrice());
                            Log.d("MainActivity", "busLineItem.getTotalPrice():=====2总价格=$:" + busLineItem.getTotalPrice());
                            Log.d("MainActivity", "busLineItem.getOriginatingStation()获取的公交起始站点====2:" + busLineItem.getOriginatingStation());
                            Log.d("MainActivity", "busLineItem.getTerminalStation()获取的公交终点站点====2:" + busLineItem.getTerminalStation());
                            if (busLineItem.getBasicPrice() == busLineItem.getTotalPrice()) {
                                feescale = "1";
                            } else {
                                feescale = "2";
                            }
                            Log.d("BuslineActivity", "选中的公交feescale=公交线路======2: " + feescale);
                            for (BusStationItem busStationItem : busLineItem.getBusStations()) {
                                Log.d("BuslineActivity", "选中的公交的所有站点信息=======34" + busStationItem.getBusStationName());
                                Log.d("BuslineActivity", "选中的公交的所有站点信息=======34" + busStationItem.getLatLonPoint());
                                Root.zfx zfx = new Root.zfx();
                                String lat = busStationItem.getLatLonPoint().getLatitude() + "";
                                String lon = busStationItem.getLatLonPoint().getLongitude() + "";
                                zfx.setLat(lat);
                                zfx.setLon(lon);
                                zfx.setName(busStationItem.getBusStationName());
                                zfxList.add(zfx);
                                Log.d("BuslineActivity", "选中的公交的所有站点经度=======34: " + lon);
                                Log.d("BuslineActivity", "选中的公交的所有站点信息=======34: " + lat);
                            }
                        }
                    }

                }
                Root root = new Root(end,TotalPrice, feescale,name , start, BasicPrice, ffxList, zfxList);
                roots.add(root);
                String json = new Gson().toJson(roots);
                mBusLineReuqest = buslineApi.requestAliPay(json)

                        .subscribe(new Observer<Base>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(Base base) {

                            }
                        });
//                jsonArray=null;
//                object=null;
//                jsonArray = new JSONArray();
//                jsonArray2 = new JSONArray();
//                jsonArray1 = new JSONArray();
//                object=new JSONObject();
//                for (int i = 0; i < roots.size(); i++) {  //遍历上面初始化的集合数据，把数据加入JSONObject里面
//                    for (int i1 = 0; i1 < roots.get(i).getFfxBeen().size(); i1++) {
//                        object2=new JSONObject();
//                        try {
//                            object2.put("lat", roots.get(i).getFfxBeen().get(i).getLat());  //从集合取出数据，放入JSONObject里面 JSONObject对象和map差不多用法,以键和值形式存储数据
//                            object2.put("lon", roots.get(i).getFfxBeen().get(i).getLon());
//                            object2.put("name", roots.get(i).getFfxBeen().get(i).getName());
//                            jsonArray2.put(object2); //把JSONObject对象装入jsonArray数组里面
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    for (int i1 = 0; i1 < roots.get(i).getZfxBeen().size(); i1++) {
//                        object1=new JSONObject();
//                        try {
//                            object1.put("lat", roots.get(i).getZfxBeen().get(i).getLat());  //从集合取出数据，放入JSONObject里面 JSONObject对象和map差不多用法,以键和值形式存储数据
//                            object1.put("lon", roots.get(i).getZfxBeen().get(i).getLon());
//                            object1.put("name", roots.get(i).getZfxBeen().get(i).getName());
//                            jsonArray1.put(object1); //把JSONObject对象装入jsonArray数组里面
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    try {
//                        object.put("end", roots.get(i).getEnd());  //从集合取出数据，放入JSONObject里面 JSONObject对象和map差不多用法,以键和值形式存储数据
//                        object.put("end_price", roots.get(i).getEnd_price());
//                        object.put("feescale", roots.get(i).getFeescale());
//                        object.put("name", roots.get(i).getName());
//                        object.put("start", roots.get(i).getStart());
//                        object.put("start_price", roots.get(i).getStart_price());
//                        object.put("ffx",jsonArray2 );
//                        object.put("zfx",jsonArray1 );
//                        jsonArray.put(object); //把JSONObject对象装入jsonArray数组里面
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                try {
//                    object.put("Root", jsonArray); //再把JSONArray数据加入JSONObject对象里面(数组也是对象)
//                    //object.put("time", "2013-11-14"); //这里还可以加入数据，这样json型字符串，就既有集合，又有普通数据
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                jsonString=null;
//                jsonString = object.toString(); //把JSONObject转换成json格式的字符串

                Log.d("MainActivity","json数据======00" + json);
                busLineQuery = new BusLineQuery(lineId, BusLineQuery.SearchType.BY_LINE_ID,
                        mCityName);// 第一个参数表示公交线路id，第二个参数表示公交线路id查询，第三个参数表示所在城市名或者城市区号
                BusLineSearch busLineSearch = new BusLineSearch(
                        MainActivity.this, busLineQuery);
                busLineSearch.setOnBusLineSearchListener(MainActivity.this);
                busLineSearch.searchBusLineAsyn();// 异步查询公交线路id
            }
        });
        busLineDialog.show();

    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    interface OnListItemlistener {
        public void onListItemClick(BusLineDialog dialog, BusLineItem item);
    }

    /**
     * 所有公交线路显示页面
     */
    class BusLineDialog extends Dialog implements View.OnClickListener {

        private List<BusLineItem> busLineItems;
        private BusLineAdapter busLineAdapter;
        private Button preButton, nextButton;
        private ListView listView;
        protected OnListItemlistener onListItemlistener;

        public BusLineDialog(Context context, int theme) {
            super(context, theme);
        }

        public void onListItemClicklistener(
                OnListItemlistener onListItemlistener) {
            this.onListItemlistener = onListItemlistener;

        }

        public BusLineDialog(Context context, List<BusLineItem> busLineItems) {
            this(context, android.R.style.Theme_NoTitleBar);
            this.busLineItems = busLineItems;
            busLineAdapter = new BusLineAdapter(context, busLineItems);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.busline_dialog);
            preButton = (Button) findViewById(R.id.preButton);
            nextButton = (Button) findViewById(R.id.nextButton);
            listView = (ListView) findViewById(R.id.listview);
            listView.setAdapter(busLineAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    onListItemlistener.onListItemClick(BusLineDialog.this,
                            busLineItems.get(arg2));
                    dismiss();

                }
            });
            preButton.setOnClickListener(this);
            nextButton.setOnClickListener(this);
            if (currentpage <= 0) {
                preButton.setEnabled(false);
            }
            if (currentpage >= busLineResult.getPageCount() - 1) {
                nextButton.setEnabled(false);
            }

        }

        @Override
        public void onClick(View v) {
            this.dismiss();
            if (v.equals(preButton)) {
                currentpage--;
            } else if (v.equals(nextButton)) {
                currentpage++;
            }
            showProgressDialog();
            busLineQuery.setPageNumber(currentpage);// 设置公交查询第几页
            busLineSearch.setOnBusLineSearchListener(MainActivity.this);
            busLineSearch.searchBusLineAsyn();// 异步查询公交线路名称
        }
    }

    /**
     * 公交线路查询结果回调
     */
    @Override
    public void onBusLineSearched(BusLineResult result, int rCode) {
        dissmissProgressDialog();
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null
                    && result.getQuery().equals(busLineQuery)) {
                for (BusLineItem busLineItem : result.getBusLines()) {
                    for (BusStationItem busStationItem : busLineItem.getBusStations()) {
                        Log.d("BuslineActivity", "公交站点名字=====" + busStationItem.getBusStationName());
                    }
                }

                if (result.getQuery().getCategory() == BusLineQuery.SearchType.BY_LINE_NAME) {
                    if (result.getPageCount() > 0
                            && result.getBusLines() != null
                            && result.getBusLines().size() > 0) {
                        busLineResult = result;
                        lineItems = result.getBusLines();
                        showResultList(lineItems);
                    }
                } else if (result.getQuery().getCategory() == BusLineQuery.SearchType.BY_LINE_ID) {

                    busLineResult = result;
                    lineItems = busLineResult.getBusLines();

                }
            }
        }
    }

    /**
     * 查询公交线路
     */
    @Override
    public void onClick(View v) {
        searchLine();
    }
}
